package com.ksxy.afingerprint.core

import android.annotation.TargetApi
import android.app.KeyguardManager
import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.os.CancellationSignal
import android.os.Handler
import java.lang.IllegalStateException
import javax.crypto.Cipher

/**
 *  author : chenyinying
 *  e-mail : me@korion.cn
 *  time   : 2018/07/06
 *  desc   :
 *  version: 1.0
 */
class FingerPrintAuthHelper(context: Context) {

    private var mContext: Context? = null
    private var mFingerprintManager: FingerprintManager? = null
    private var mKeyguardManager: KeyguardManager? = null

    init {
        mContext = context
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mFingerprintManager = mContext!!.getSystemService(FingerprintManager::class.java)
            mKeyguardManager = mContext!!.getSystemService(KeyguardManager::class.java)
        }
        if(mFingerprintManager == null || mKeyguardManager == null){
            throw IllegalStateException("Init FingerPrintAuthHelper object fail, make sure that Android SDK is greater than 23")
        }
    }

    public fun checkSupportFingerPrintAuth(): Boolean{
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return false
        }
        if(mFingerprintManager!!.isHardwareDetected
                && mFingerprintManager!!.hasEnrolledFingerprints()
                && mKeyguardManager!!.isKeyguardSecure()){
            return true
        }
        return false
    }

    @TargetApi(Build.VERSION_CODES.M)
    public fun authenticate(cipher: Cipher,
                            callback: FingerprintManager.AuthenticationCallback,
                            handler: Handler?): CancellationSignal{
        val cipherObj = FingerprintManager.CryptoObject(cipher)
        val cancel = CancellationSignal()
        mFingerprintManager?.authenticate(cipherObj, cancel, 0, callback, handler)
        return cancel
    }

    companion object {
        fun from(context: Context): FingerPrintAuthHelper {
            return FingerPrintAuthHelper(context)
        }
    }
}